package cn.edu.buu.hospital.web;

import cn.edu.buu.hospital.entity.Doctor;
import cn.edu.buu.hospital.service.DepartmentService;
import cn.edu.buu.hospital.service.DoctorService;
import cn.edu.buu.hospital.service.HospitalService;
import cn.edu.buu.hospital.service.VisitService;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 医生管理控制器
 */
@Controller
@RequestMapping("/doctor")
public class DoctorController {

    @Autowired
    private DoctorService doctorService;
    
    @Autowired
    private DepartmentService departmentService;
    
    @Autowired
    private HospitalService hospitalService;
    
    @Autowired
    private VisitService visitService;

    // 跳转到新增医生页面
    @GetMapping("/toAdd")
    public String toAdd(Model model) {
        // 添加科室列表到model中
        model.addAttribute("departmentList", departmentService.findAll());
        // 添加医院列表到model中
        model.addAttribute("hospitalList", hospitalService.findAll());
        return "backend/doctor/add";
    }

    // 新增医生
    @PostMapping("/add")
    @Transactional
    public String add(Doctor doctor, Model model) {
        try {
            doctorService.add(doctor);
            return "redirect:find";
        } catch (Exception e) {
            // 保存错误信息到session，因为重定向会丢失model
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            request.getSession().setAttribute("addError", "新增失败: " + e.getMessage());
            request.getSession().setAttribute("addDoctor", doctor);
            return "redirect:find";
        }
    }

    // 查询医生列表
    @RequestMapping(value = "/find", method = {RequestMethod.GET, RequestMethod.POST})
    public String find(Model model,
                       @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                       @RequestParam(value = "editId", required = false) Long editId,
                       @RequestParam(value = "edit", required = false) Boolean edit,
                       Doctor condition) {
        int pageSize = 5;
        // 初始化查询条件
        if (condition == null) {
            condition = new Doctor();
        }
        PageInfo<Doctor> pageInfo = doctorService.find(pageNum, pageSize, condition);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("condition", condition);
        
        // 获取session信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        
        // 处理编辑参数和错误信息
        // 先尝试从session中获取编辑的医生信息
        Doctor sessionDoctor = (Doctor) session.getAttribute("doctor");
        if (sessionDoctor != null) {
            model.addAttribute("doctor", sessionDoctor);
            session.removeAttribute("doctor");
        } else if (editId != null || Boolean.TRUE.equals(edit)) {
            // 如果有editId参数或edit=true，则查询医生信息
            if (editId != null) {
                Doctor doctor = doctorService.findById(editId);
                if (doctor == null) {
                    doctor = new Doctor();
                    doctor.setDoctorId(editId);
                }
                model.addAttribute("doctor", doctor);
            }
        }
        
        // 从session中获取错误信息
        String modifyError = (String) session.getAttribute("modifyError");
        if (modifyError != null) {
            model.addAttribute("error", modifyError);
            session.removeAttribute("modifyError");
        }
        
        String addError = (String) session.getAttribute("addError");
        if (addError != null) {
            model.addAttribute("error", addError);
            session.removeAttribute("addError");
        }
        
        String error = (String) session.getAttribute("error");
        if (error != null) {
            model.addAttribute("error", error);
            session.removeAttribute("error");
        }
        
        // 添加科室列表到model中
        model.addAttribute("departmentList", departmentService.findAll());
        // 添加医院列表到model中
        model.addAttribute("hospitalList", hospitalService.findAll());
        
        return "backend/doctor/list";
    }

    // 根据ID查询医生（用于编辑）
    @GetMapping("/findById")
    public String findById(@RequestParam("doctorId") Long doctorId, HttpSession session) {
        // 从数据库查询医生信息
        Doctor doctor = doctorService.findById(doctorId);
        if (doctor == null) {
            doctor = new Doctor();
            doctor.setDoctorId(doctorId);
        }
        // 将医生信息存储到session中，以便在列表页的模态框中显示
        session.setAttribute("doctor", doctor);
        // 重定向到列表页，带上编辑参数
        return "redirect:find?edit=true";
    }

    // 修改医生信息
    @PostMapping("modify")
    // 注意：Controller层不需要添加@Transactional注解，事务应该在Service层控制
    public String modify(Doctor doctor, HttpSession session) {
        System.out.println("接收到医生编辑请求，医生ID: " + doctor.getDoctorId());
        try {
            doctorService.modify(doctor);
            System.out.println("医生编辑成功，医生ID: " + doctor.getDoctorId());
            return "redirect:find";
        } catch (RuntimeException e) {
            System.err.println("医生编辑业务异常: " + e.getMessage());
            e.printStackTrace();
            // 捕获运行时异常，将错误信息和医生信息存入session
            session.setAttribute("modifyError", e.getMessage());
            session.setAttribute("doctor", doctor);
            // 重定向回列表页并带上编辑参数
            return "redirect:find?editId=" + doctor.getDoctorId();
        } catch (Exception e) {
            System.err.println("医生编辑系统异常: " + e.getMessage());
            e.printStackTrace();
            // 捕获其他异常
            session.setAttribute("modifyError", "系统错误，请稍后重试");
            session.setAttribute("doctor", doctor);
            return "redirect:find?editId=" + doctor.getDoctorId();
        }
    }

    // 删除医生
    @GetMapping("/removeById")
    @Transactional
    public String removeById(@RequestParam("doctorId") Long doctorId) {
        try {
            // 检查是否有关联的排班记录
            Doctor doctor = doctorService.findById(doctorId);
            if (doctor != null) {
                // 这里可以添加检查逻辑，例如检查是否有关联的排班
                // 由于系统设计可能不同，暂时先直接删除
                doctorService.removeById(doctorId);
            }
            return "redirect:find";
        } catch (Exception e) {
            // 保存错误信息到session
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            request.getSession().setAttribute("error", "删除失败: " + e.getMessage());
            return "redirect:find";
        }
    }
}